<!-- chatList.html -->
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
	<link rel="stylesheet" href="../../css/weui.min.css">
	<link rel="stylesheet" href="../../css/jquery-weui.min.css">
	<link rel="stylesheet" href="../../css/rongYunUI.css">
</head>
<body id="content_div">
	<div class="weui-pull-to-refresh-layer">
		<div class='pull-to-refresh-arrow'></div>
		<div class='pull-to-refresh-preloader'></div>
    </div>
	<ul id="message_list" class="message-list scrollbar">
	</ul>
	<div class="zhan-wei-div"></div>
	<div class="bottom-tool-div">
		<div class="top-line"></div>
		<div class="bottom-content">
			<div class="bottom-voice-div" onclick="onSwitchInputMode()">
				<img id="input_mode_img" class="tool-btn" src="../../image/icon_voice.png">
			</div>
			<div class="bottom-button-div">
				<div id="show-actions" class="tool-btn-div tool-btn-div-left" onclick="onSelectImageClick()">
					<div class="tool-sub-div">
						<img class="tool-btn" src="../../image/icon_add_img.png">
					</div>
				</div>
				<a id="sendBtn" href="javascript:;" class="send-btn weui_btn weui_btn_mini weui_btn_primary" onclick="onSendClick()">发送</a>
			</div>
			<div class="bottom-input-div">
				<input id="chat_message" type="text" name="" class="message-input" onkeypress="onKeyClick()" onclick="setupKeyboardEjectClick()">
				<div class="voice-record-div" hidden="hidden">
					<a id="voice_revord_btn" href="javascript:;" class="weui_btn weui_btn_default voice-record-btn" ontouchstart="voiceRecordTouchDown()" ontouchend="voiceRecordTouchUp()">按住 说话</a>
				</div>
			</div>
		</div>
	</div>
</body>
<script src="../../script/jquery.min.js"></script>
<script src="../../script/jquery-weui.min.js"></script>
<script src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/MD5.js"></script>
<script type="text/javascript" src="../../script/requestTool.js"></script>
<!-- <script src="../../script/rongYun.js"></script> -->
<script type="text/javascript">
	var playAnimationduration = 300;//动画切换间隔毫秒
	var timeInterval;
	var isPlayVoiceAnimation = false;//是否正在播放语音动画
	var currentPlayVoiceId = '';//当前正在播放的语音
	var currentPlaySendStatus = '';
	function playVoice(msgId, voicepath, duration, sendstatus){
		if (msgId == currentPlayVoiceId) {
			if (isPlayVoiceAnimation == true) {//正在播放则不操作
				return;
			}
		}else{//不是同一个语音，则停止旧的
			if (currentPlayVoiceId != '') {
				if (isPlayVoiceAnimation == true) {
					stopVoice(currentPlayVoiceId, currentPlaySendStatus);//停止动画
					api.stopPlay();
				}
			}
			currentPlayVoiceId = msgId;
			currentPlaySendStatus = sendstatus;
		}
		//开始播放
		api.startPlay({
		    path: voicepath
		}, function(ret, err) {
		    if (err) {
		    	api.toast({
		    	    msg: '语音播放失败'
		    	});
		    }
		});
		isPlayVoiceAnimation = true;//正在播放
		var msg = $('#voice_msg'+msgId);
		var currentTime = 0;
		var endTime = duration * 1000;
		var currentIndex = 1;
		timeInterval = setInterval(function(){
			if (currentTime < endTime) {
				var msgImgSrc = '../../image/voice_'+sendstatus+'0'+currentIndex+'.png';
				msg.attr('src', msgImgSrc);
			}else{
				clearInterval(timeInterval);
				var msgImgSrc = '../../image/voice_'+sendstatus+'03.png';
				msg.attr('src', msgImgSrc);
				isPlayVoiceAnimation = false;//播放结束
			}
			currentIndex += 1;
			if (currentIndex > 3) {//如果下标大于3则重新归1
				currentIndex = 1;
			}
			currentTime += playAnimationduration;
		}, playAnimationduration);
	}
	function stopVoice(msgId, sendstatus){
		var msg = $('#voice_msg'+msgId);
		clearInterval(timeInterval);
		var msgImgSrc = '../../image/voice_'+sendstatus+'03.png';
		msg.attr('src', msgImgSrc);
		isPlayVoiceAnimation = false;//播放停止
	}
</script>
<script type="text/javascript">
	var currentUid;
	var userNormalIcon = '../../image/icon_touxiang.png';
	var usersData = new Object();//存储所有用户数据
	var messageArr = new Array();
	var groupId;
	var groupName;
	var rongCloud;
	var isKeyword = true;//默认是键盘模式（false即代表语音模式）
	apiready = function(){
	    parpreData(function(status){
	    	if (status == 1) {
				rongCloud = api.require('rongCloud2');
	    		setupCurrentUid();
			    setupMsgNotifi();
			    loadLastMessages();
			    setupPullDownClick();
			    //设置状态监听
			    setupConnectStatusLinster();
	    	}else{
	    		api.toast({
				    msg: '获取群组信息失败'
				});
	    	}
	    });
	}
	//切换输入模式 键盘或语音
	function onSwitchInputMode(){
		if(isKeyword == true){
			isKeyword = false;
			$('#input_mode_img').attr('src', '../../image/icon_keyword.png');
			$('.voice-record-div').show();
		}else {
			isKeyword = true;
			$('#input_mode_img').attr('src', '../../image/icon_voice.png');
			$('.voice-record-div').hide();
		}
	}
	//录音按钮按下
	function voiceRecordTouchDown(){
		$('#voice_revord_btn').text('松开 结束');
		api.startRecord();
	}
	//松开录音按钮
	function voiceRecordTouchUp(){
		$('#voice_revord_btn').text('按住 说话');
		api.stopRecord(function(ret, err) {
		    if (ret) {
		        var voicePath = ret.path;
		        var duration = ret.duration;
		        sendVoiceMsg(voicePath, duration);
		    }
		});
	}
	//发送语音消息
	function sendVoiceMsg(voicePath, duration){
		var msgData;
		rongCloud.sendVoiceMessage({
		    conversationType: 'GROUP',
		    targetId: groupId,
		    voicePath: voicePath,
		    duration: duration,
		    extra: ''
		}, function(ret, err) {
		    if (ret.status == 'prepare'){
		        // api.toast({ msg: JSON.stringify(ret.result.message) });
		        msgData = ret.result.message;
		    }else if (ret.status == 'success'){
		        messageArr.splice(0,0,msgData);
		        $('#message_list').append(messageHtmlWithMsgData(msgData));
		        setupVoiceClick(msgData);
		        scrollToTheBottom();
		    }else if (ret.status == 'error'){
		    	getConnnectStatus(function(cResult){
		    		if (cResult == 0) {
		    			api.toast({
				    	    msg: '语音消息发送失败：'+err.code
				    	});
		    		}
		    	});
		    }
		});
	}
	//设置语音点击事件
	function setupVoiceClick(msgData){
		$('#voiceid'+msgData.messageId).on('click', function(event) {
			var msgid = $(this).attr('msgid');
			var voicepath = $(this).attr('voicepath');
			var duration = $(this).attr('duration');
			duration = parseInt(duration);
			var sendstatus = $(this).attr('sendstatus');
			playVoice(msgid, voicepath, duration, sendstatus);
		});
	}
	function parpreData(callBack){//准备数据
		var groupType = api.pageParam.groupType;
		var params;
		var groupUrl;
		if (groupType == 'teacher') {
			var teacherGroupId = api.pageParam.teacherGroupId;
			if (teacherGroupId != null) {//如果数据已在首页加载，则不重复加载
				groupId = teacherGroupId;
				usersData = api.pageParam.teacherGroupObjc;
				groupName = api.pageParam.teacherGroupName;
				callBack(1);
				return;
			}
			params = {
				jid : $api.getStorage('cfnetppjxid')
			};
			groupUrl = getRongCloudTeacherGroup;
		}else{
			params = {
				uid : $api.getStorage('cfnetppuid'),
				jid : $api.getStorage('cfnetppjxid'),
				cid : api.pageParam.cid,
				pid : api.pageParam.pid
			};
			groupUrl = getRongCloudCourseGroup;
		}
		// alert(JSON.stringify(params));
		cfnetppPOST(groupUrl, params, true, function(data, status){
			// alert(JSON.stringify(data));
			if (status == 'success') {
				if (data.code == 200) {
					var groupData = data.data;
					groupId = groupData.group;
					groupName = groupData.groupname;
					var userList = groupData.uname;
					if (userList != null && userList != undefined && userList.constructor == Array && userList.length > 0) {
						for (var i = userList.length - 1; i >= 0; i--) {
							var userData = userList[i];
							usersData[userData.uid] = userData;
						}
						callBack(1);
					}else{
						callBack(0);
					}
				}else{
					callBack(0);
				}
			}else{
				callBack(0);
			}
		});
	}
	function setupCurrentUid(){
		// currentUid = $api.getStorage('rongYunUid');
		currentUid = $api.getStorage('cfnetppuid');
		// api.toast({
		//     msg: currentUid,
		//     duration: 2000,
		//     location: 'bottom'
		// });
	}
	function loadLastMessages(){
		setTimeout(function() {
			loadLastestMessage();
		}, 1000);
	}
	//设置下拉加载
	function setupPullDownClick(){
		$(document.getElementById('content_div')).pullToRefresh().on("pull-to-refresh", function() {
			loadHistryMessage();
		});
	}
	function loadHistryMessage(){
		var oldestMessageId;
		if (messageArr.length == 0) {
			oldestMessageId = '-1';
		}else{
			oldestMessageId = messageArr[messageArr.length - 1].messageId;
		}
		rongCloud.getHistoryMessages({
		    conversationType: 'GROUP',
		    targetId: groupId,
		    oldestMessageId: oldestMessageId,
		    count: 20
		}, function(ret, err) {
			$(document.getElementById('content_div')).pullToRefreshDone();
		    var messages = ret.result;
		    if (messages != null && messages.constructor == Array && messages.length > 0) {
		    	messageArr = messageArr.concat(messages);
		    	setupHistryMessage(messages);
		    }
		});
	}
	function loadLastestMessage(){
		rongCloud.getLatestMessages({
		    conversationType: 'GROUP',
		    targetId: groupId,
		    count: 20
		}, function(ret, err) {
		    var messages = ret.result;
		    if (messages != null && messages.constructor == Array && messages.length > 0) {
		    	messageArr = messageArr.concat(messages);
		    	setupLastestMessage(messages);
		    }
		});
	}
	//设置历史聊天记录
	function setupHistryMessage(messages){
		for (var i = 0; i < messages.length; i++) {
			var msgData = messages[i];
			$('#message_list').prepend(messageHtmlWithMsgData(msgData));
			setupImageClick(msgData);
			setupVoiceClick(msgData);
		}
		var marginTop = $('#'+messages[0].messageId).offset().top - 60;
		window.scrollTo(0,marginTop);
	}
	//设置最近聊天记录
	function setupLastestMessage(messages){
		for (var i = 0; i < messages.length; i++) {
			var msgData = messages[i];
			$('#message_list').prepend(messageHtmlWithMsgData(msgData));
			setupImageClick(msgData);
			setupVoiceClick(msgData);
		}
		setTimeout(function(){
			scrollToTheBottom();
		}, 500);
	}
	//设置键盘弹出后页面滑动至底部
	function setupKeyboardEjectClick(){
		setTimeout(function(){
			scrollToTheBottom();
		}, 300);
	}
	//滚动到底部
	function scrollToTheBottom(){
		var messageList = document.getElementById('message_list');
		window.scrollTo(0,messageList.scrollHeight);
	}
	function customUI(){
		var msgListHeight = $(window).height() - $('.bottom-tool-div').height();
		$('.message-list').css('max-height', msgListHeight);
	}
	function setupMsgNotifi(){
		// alert('设置消息通知');
		api.addEventListener({
		    name: 'RongCloudNewMsgNotifi'
		}, function(ret, err){
			// alert('接收到消息通知'+JSON.stringify(ret));
		    var message = ret.value.msgRet.result.message;
		    var targetId = message.targetId;
		    if (targetId != groupId) {//如果不是该回话则return
		    	return;
		    }
			$('#message_list').append(messageHtmlWithMsgData(message));
			setupImageClick(message);
			setupVoiceClick(message);
			if (isScrollBottom(message.messageId) == true) {
				scrollToTheBottom();
			}
		});
		// receiveMsg(function(ret, err){
		// 	var message = ret.result.message;
		// 	messageArr.splice(0,0,message);
		// 	$('#message_list').append(messageHtmlWithMsgData(message));
		// 	setupImageClick(message);
		// 	if (isScrollBottom(message.messageId) == true) {
		// 		scrollToTheBottom();
		// 	}
		// });
		// joinChatGroup(groupId, groupName);//加入当前群组
		api.sendEvent({
		    name: 'RongCloudJoinGroupNotifi',
		    extra: {
		        groupId: groupId,
		        groupName: groupName
		    }
		});
	}
	function isScrollBottom(msgId) {
		// api.toast({
		//     msg: document.getElementById(msgId).offsetTop+'\n'+document.documentElement.clientHeight+'\n'+document.body.scrollTop
		// });
	   	if (document.getElementById(msgId).offsetTop - document.documentElement.clientHeight <= document.body.scrollTop) {
	   	    return true;
	   	} else {
	       	return false;
	   	}
	}
	function unameWithData(data){
		if (data == undefined || data == null || data == '') {
			return '(未知用户)';
		}
		var uname = data.uname;
		if (!nameIsNotNull(uname)) {
			uname = data.rename;
			if (!nameIsNotNull(uname)) {
				uname = data.realname;
				if (!nameIsNotNull(uname)) {
					uname = '(未知用户)';
				}
			}
		}
		return uname;
	}
	function nameIsNotNull(name){
		if (name == null || name == undefined || name == ''){
			return false;
		}
		return true;
	}
	function iconImageWithData(data){
		if(data == undefined || data == null || data == ''){
			return userNormalIcon;
		}
		var picurl = data.picurl;
		if (picurl == null || picurl == undefined || picurl == '') {
			picurl = userNormalIcon;
		}
		return picurl;
	}
	function messageHtmlWithMsgData(msgData){
		// alert(JSON.stringify(msgData));
		var senderUserId = msgData.senderUserId;//发送者id
		var senderUserData = usersData[senderUserId];
		if (senderUserData == undefined || senderUserData == null) {
			var currentSendUid = (senderUserId.split("_"))[0];
			senderUserData = usersData[currentSendUid];
		}
		var userIcon = iconImageWithData(senderUserData);
		var userName = unameWithData(senderUserData);
		var messageClass = 'message-other-div';
		var arrowDirection = 'left';
		var voiceDirection = 'left';
		if (senderUserId == currentUid) {
			messageClass = 'message-self-div';
			arrowDirection = 'right';
			voiceDirection = 'right';
		}
		var msgContent = '';
		if (msgData.objectName == 'RC:TxtMsg') {//文字消息
			msgContent = '<p class="message-content-p">'+
								msgData.content.text+
							'</p>';
		}else if (msgData.objectName == 'RC:ImgMsg') {//图片消息
			msgContent = '<div class="message-content-img-div">'+
							'<img id="pic'+msgData.messageId+'" class="message-content-img" src="'+msgData.content.imageUrl+'">'+
						'</div>';
			arrowDirection = (arrowDirection == 'right') ? 'img' : 'left';
		}else if (msgData.objectName == 'RC:VcMsg'){//语音消息
			var voiceContent = msgData.content;
			var voicePath = voiceContent.voicePath;
			var duration = voiceContent.duration;
			msgContent = '<p id="voiceid'+msgData.messageId+'" class="message-content-p message-content-voice" msgid="'+msgData.messageId+'" voicepath="'+voicePath+'" duration="'+duration+'" sendstatus="'+voiceDirection+'">'+
								'<img id="voice_msg'+msgData.messageId+'" class="voice-message-img" src="../../image/voice_'+voiceDirection+'03.png">'+
							'</p>';
		}else{
			return '';
		}
		return '<div id="'+msgData.messageId+'" class="message-base-div">'+
				'<div class="'+messageClass+'">'+
					'<img src="'+userIcon+'" class="user-icon" />'+
					'<div class="message-name-div">'+
						'<p class="message-name-p">'+userName+'</p>'+
					'</div>'+
					'<div class="message-div">'+
						'<img src="../../image/icon_message_arrow_'+arrowDirection+'.png" class="message-arrow">'+
						'<div class="message-content">'+
							msgContent+
						'</div>'+
					'</div>'+
				'</div>'+
			'</div>';
	}
	function onSendClick(){
		var message = $('#chat_message').val();
		if (message == '') {//如果没输入内容
			return;
		}
		var msgData;
		rongCloud.sendTextMessage({
		    conversationType: 'GROUP',
		    targetId: groupId,
		    text: message,
		    extra: ''
		}, function(ret, err) {
		    if (ret.status == 'prepare'){
		        // api.toast({ msg: JSON.stringify(ret.result.message) });
		        msgData = ret.result.message;
		    }else if (ret.status == 'success'){
	    		$('#chat_message').val('');//清空输入框
		        messageArr.splice(0,0,msgData);
		        $('#message_list').append(messageHtmlWithMsgData(msgData));
		        scrollToTheBottom();
		    }else if (ret.status == 'error'){
		    	getConnnectStatus(function(cResult){
		    		if (cResult == 0) {
		    			api.toast({
				    	    msg: '发送消息失败：'+err.code
				    	});
		    		}
		    	});
				// if (err.code == '22406'){//未知错误（不在群组，但是用户确实在群组中）
				// 	$('#chat_message').val('');//清空输入框
			 //        messageArr.splice(0,0,msgData);
			 //        $('#message_list').append(messageHtmlWithMsgData(msgData));
			 //        scrollToTheBottom();
				// }
		    }
		});
	}
	function setupImageClick(msgData){
		$('#pic'+msgData.messageId).on('click',function(){
			var picUrl = $(this).attr('src');
			openImageController(picUrl, 0);
		});
	}
	//图片预览
	function openImageController(imgages, i) {
		imgages = arraryWithObjc(imgages);
		var imageBrowser = api.require('imageBrowser');
		imageBrowser.openImages({
			imageUrls : imgages,
			showList : false,
			activeIndex : i,
		}, function(ret, err) {
		});
	}
	function arraryWithObjc(str) {
		if (str.constructor == Object) {
			return [];
		} else if (str.constructor == Array) {
			return str;
		} else if (str.constructor == String) {
			return str.split(",");
		}
		return [];
	}
	function onKeyClick(){
		if (event.keyCode == 13) {//回车
			onSendClick();
		}
	}
	function selectPicture(sourceType){
		api.getPicture({
		    sourceType: sourceType,
		    encodingType: 'jpg',
		    mediaValue: 'pic',
		    destinationType: 'url',
		    allowEdit: true,
		    quality: 50,
		    saveToPhotoAlbum: false
		}, function(ret, err){
		    if(ret){
		    	var photoPath = ret.data;
		    	if (photoPath != '') {
		    		sendPictureMessage(photoPath);
		    	}
		    }
		});
	}
	function onSelectImageClick(){
        $.actions({
          	// title: "选择操作",
          	onClose: function() {

          	},
          	actions: [
            {
              	text: "拍照",
              	className: "actionSheet-title",
              	onClick: function() {
                	selectPicture('camera');
              	}
            },
            {
              	text: "从相册选择",
              	className: "actionSheet-title",
              	onClick: function() {
                	selectPicture('album');
              	}
            }
          ]
        });
	}
	function sendPictureMessage(picPath){
		var messageData;
		rongCloud.sendImageMessage({
		    conversationType: 'GROUP',
		    targetId: groupId,
		    imagePath: picPath,
		    extra: ''
		}, function(ret, err) {
		    if (ret.status == 'prepare'){
		        // api.toast({ msg: JSON.stringify(ret.result.message) });
		        messageData = ret.result.message;
		    }
		    else if (ret.status == 'progress'){
		        // api.toast({ msg: ret.result.progress });
		    }
		    else if (ret.status == 'success'){
		        // api.toast({ msg: ret.result.message.messageId });
		        messageArr.splice(0,0,messageData);
		        $('#message_list').append(messageHtmlWithMsgData(messageData));
		        setupImageClick(messageData);
		        setTimeout(function(){
			        scrollToTheBottom();
		        }, 1000);
		    }
		    else if (ret.status == 'error'){
		    	getConnnectStatus(function(cResult){
		    		if (cResult == 0) {
		    			api.toast({ msg: '发送图片失败：'+ err.code });
		    		}
		    	});
				// if(err.code == '22406'){
				// 	messageArr.splice(0,0,messageData);
				// 	$('#message_list').append(messageHtmlWithMsgData(messageData));
				// 	setupImageClick(messageData);
				// 	setTimeout(function(){
				// 		scrollToTheBottom();
				// 	}, 1000);
				// }
		    }
		});
	}
	function getConnnectStatus(callBack){
		rongCloud.getConnectionStatus(function(ret, err) {
		    var connectionStatus = ret.result.connectionStatus;
		    if (connectionStatus == 'KICKED') {//用户账户在其他设备登录
		    	api.toast({
				    msg: '当前账户在其他设备上登录，请重新登录',
				    duration: 3000,
				    location: 'bottom'
				});
				if (callBack) {
		    		callBack(1);
		    	}
		    }else if(connectionStatus == 'DISCONNECTED'){
		    	api.toast({
				    msg: '当前连接已断开',
				    duration: 3000,
				    location: 'bottom'
				});
				if (callBack) {
		    		callBack(1);
		    	}
		    }else if(connectionStatus == 'NETWORK_UNAVAILABLE'){
		    	api.toast({
				    msg: '当前网络不可用',
				    duration: 3000,
				    location: 'bottom'
				});
				if (callBack) {
		    		callBack(1);
		    	}
		    }else if(connectionStatus == 'SERVER_INVALID'){
		    	api.toast({
				    msg: '服务器异常或无法连接',
				    duration: 3000,
				    location: 'bottom'
				});
				if (callBack) {
		    		callBack(1);
		    	}
		    }else if(connectionStatus == 'TOKEN_INCORRECT'){
		    	api.toast({
				    msg: '当前用户Token不正确',
				    duration: 3000,
				    location: 'bottom'
				});
				if (callBack) {
		    		callBack(1);
		    	}
		    }else{
		    	if (callBack) {
		    		callBack(0);
		    	}
		    }
		});
	}
	//设置状态监听
	function setupConnectStatusLinster(){
		rongCloud.setConnectionStatusListener(function(ret, err) {
		    var connectionStatus = ret.result.connectionStatus;
		    if (connectionStatus == 'KICKED') {//用户账户在其他设备登录
		    	api.toast({
				    msg: '当前账户在其他设备上登录，请重新登录',
				    duration: 5000,
				    location: 'bottom'
				});
		    }
		});
	}
</script>
</html>
